/**
 * jims.
 */
package com.thinkgem.jeesite.modules.sys.security;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.Token;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by lhl on 2017/6/15.
 * 增加了kisso后增加了这个类，在spring-context-shiro.xml中增加的一行shiroFilter过滤userFilter就是对应本类。
 */
@Service
public class UserFilter extends org.apache.shiro.web.filter.authc.UserFilter {
    private SystemService systemService;
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpRequest= (HttpServletRequest) request;
        HttpServletResponse httpRespons= (HttpServletResponse) response;
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            Token token = SSOHelper.getToken(httpRequest);
            if(subject.getPrincipal() != null && token==null){
                SystemAuthorizingRealm.Principal principal=(SystemAuthorizingRealm.Principal)subject.getPrincipal();
                SSOToken st = new SSOToken(httpRequest,principal.getId());
                SSOHelper.setSSOCookie(httpRequest,httpRespons, st, false);
            }
            if(token!=null && subject.getPrincipal() == null){
                    UsernamePasswordToken token1 = new UsernamePasswordToken();
                    token1.setId(token.getUid());
                    token1.setIsLogin(true);
                    subject.login(token1);
            }

            return subject.getPrincipal() != null;
        }
    }
    /**
     * 获取系统业务对象
     */
    public SystemService getSystemService() {
        if (systemService == null){
            systemService = SpringContextHolder.getBean(SystemService.class);
        }
        return systemService;
    }
}
